const express=require('express');
const mongoose = require('mongoose');
const articleSchema = require('../model/articleDb');
const userSchema = require('../model/userDb');
const common = require('../commons/common');
const urlLib = require('url');//用于解析get所携带的参数


//4.连接数据库（mongoodb）
mongoose.connect("mongodb://localhost/myblog");
var db = mongoose.connection;
db.on('error', function () {
  throw new Error('unable to connect to database at ');
});
db.on('open', function () {
  console.log("连接数据库成功");
});

var article= db.model('article1',articleSchema);
var users = db.model('user',userSchema);


module.exports=function (){
  var router=express.Router();
  
  //添加文章
  router.post('/insert', function (req, res){
    //var article=new articleSchema();
    var newComment = {
    title: req.body.title,
    author : req.body.author,
    type : req.body.type,
    text : req.body.text,
    time : req.body.time
  };
  var commentEntity = new article(newComment);
  commentEntity.save(function (error,data) {         
    if(error){
      res.status(200).send({state:false,mes:"添加文章失败"}).end();
    }else{
      res.status(200).send({state:true,mes:"添加文章成功"}).end();
    }
  });
    //res.send(urlLib.parse(req.url,true));//true表示将参数解析成json格式
    //res.render('./1.ejs', {title: '我是标题', a: 12, b: 5}); //使用render时需要设置模板引擎，否则会报错
  });
  
  //查询所有文章
  router.get('/select', function (req, res){
    var count = urlLib.parse(req.url,true).query.count;
    //var type = urlLib.parse(req.url,true).query.type;
    article.find({},function(error,data){
      if(error){
        res.send({state:false,mes:"查询失败"}).end();
      }else{
        res.send({state:true,mes:data}).end();
      }
    });
  });

  //按照id查询文章
  router.get('/selectOne', function (req, res){
      var id = urlLib.parse(req.url,true).query.id;
      article.find({_id:id},function(error,data){
        if(error){
          res.send("查询失败"+"======>"+error).end();
        }else{
          res.send(data).end();
        }
      });
  });

  //删除文章
  router.post('/delete', function (req, res){
    var articleId = req.body.articleId;
    article.remove({_id:articleId},function(error){
      if(error){
        res.send({state:false,mes:"删除失败"}).end();
      }else{
        res.send({state:true,mes:"删除成功"}).end();
      }
    });
  });

  //后台登录
  router.post('/login', function (req, res){
    var username = req.body.username;
    var password = common.md5(common.md5(req.body.password));
    users.find({username:username},function(error,data){
      if(error){
        res.send({state:false,mes:"登录失败"}).end();
      }else{
        if(data.length>0){
          if(data[0].password==password){
            res.send({state:true,mes:"登录成功"}).end();
          }else{
            res.send({state:false,mes:"密码错误"}).end();
          }
        }else{
          res.send({state:false,mes:"没有该用户"}).end();
        }
        //res.send(data).end();
      }
    });
  });

  //后台添加管理员
  router.post('/register', function (req, res){
    var password = common.md5(common.md5(req.body.password));
    var newUsers={
      username : req.body.username,
      password : password,
      time : new Date()
    };
    var userEntity = new users(newUsers);
    userEntity.save(function(error,data){
      if(error){
        res.send('插入失败！'+'======>'+error).end();
      }else{
        res.send('插入成功！').end();
      }
    });
  });

  return router;
};
